<template>
<!--基础信息-->
  <div class="m-t20">
      <el-card class="card-box" shadow="never">
          <el-form
              :disabled="!isEdit"
              :model="formInline"
              ref="formInlineRef"
              :rules="projectRules"
              class="demo-form-inline"
              label-width="180px"
          >
              <el-row>
                  <el-col :span="8">
                      <el-form-item label="关联项目集" prop="projectSetId">
                          <el-select
                              v-model="formInline.projectSetId"
                              clearable
                              filterable
                              placeholder="关联项目集"
                          >
                              <el-option
                                  v-for="item in state.projectSetsList"
                                  :key="item.projectSetId"
                                  :label="item.projectSetName"
                                  :value="item.projectSetId"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目名称" prop="projectName">
                          <el-input
                              v-model="formInline.projectName"
                              placeholder="请输入项目名称"
                          >
                          </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目编号">
                          <el-input v-model="formInline.projectId" placeholder="">
                          </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目分类" prop="projectTypeId">
                          <el-select
                              v-model="formInline.projectTypeId"
                              clearable
                              placeholder=""
                              @change="projectTypeChange"
                          >
                              <el-option
                                  v-for="item in state.typeList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="业务单元" prop="businessUnit">
                          <el-select
                              v-model="formInline.businessUnit"
                              clearable
                              filterable
                              placeholder="业务单元"
                          >
                              <el-option
                                  v-for="(item, index) in businessUnitList"
                                  :key="index"
                                  :label="item.businessUnitName"
                                  :value="item.businessUnitId"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="计划实施时间范围" prop="time">
                          <el-date-picker
                              v-model="formInline.time"
                              @change="handelChangeTime"
                              type="datetimerange"
                              start-placeholder="开始时间"
                              end-placeholder="结束时间"
                              format="YYYY-MM-DD"
                              value-format="YYYY-MM-DD"
                              size="large"
                          />
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目位置" prop="streetCode">
                          <el-select
                              v-model="formInline.streetCode"
                              clearable
                              placeholder="项目位置"
                              @change="streerChange"
                          >
                              <el-option
                                  v-for="item in state.streetList"
                                  :value="item.value"
                                  :key="item.value"
                                  :label="item.label"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目详细地址" prop="address">
                          <el-input
                              v-model="formInline.address"
                              placeholder="请输入项目详细地址"
                          />
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="拟计划总投额" prop="projectAmount">
                          <el-input
                              v-model="formInline.projectAmount"
                              @input="formInline.projectAmount = limitInputNum(formInline.projectAmount,13,4,true)"
                              placeholder="请输入拟计划总投额"
                          />
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目立项部门">
                          <el-select
                              v-model="formInline.departmentId"
                              clearable
                              disabled
                              placeholder="项目立项部门"
                              @change="departmentIdChange(formInline.departmentId)"
                          >
                              <el-option
                                  v-for="item in state.allDepartmentList"
                                  :key="item.departmentId"
                                  :label="item.departmentName"
                                  :value="item.departmentId"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目负责人" prop="responsibleUserId">
                          <el-select
                              v-model="formInline.responsibleUserId"
                              clearable
                              filterable
                              placeholder="项目负责人"
                          >
                              <el-option
                                  v-for="item in state.departmentPersonList"
                                  :key="item.userId"
                                  :label="item.userName"
                                  :value="item.userId+''"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="年度计划投资额" prop="yearAmount">
                          <el-input
                              v-model.number="formInline.yearAmount"
                              placeholder="请输入年度计划投资额"
                          />
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目性质" prop="projectNature">
                          <el-select
                              v-model="formInline.projectNature"
                              clearable
                              placeholder="请选择项目性质"
                          >
                              <el-option
                                  v-for="item in state.projectNatureList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                              <el-option
                                  v-if="formInline.projectTypeId === '1'"
                                  v-for="item in state.projectNatureList2"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="项目新增类型" prop="projectAddType">
                          <el-select
                              v-model="formInline.projectAddType"
                              clearable
                              placeholder="项目新增类型"
                          >
                              <el-option
                                  v-for="item in state.projectAddTypeList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="计划状态" prop="planStatus">
                          <el-select
                              v-model="formInline.planStatus"
                              clearable
                              placeholder="计划状态"
                          >
                              <el-option
                                  v-for="item in state.planStatusList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="投资内容" prop="investContent">
                          <el-select
                              v-model="formInline.investContent"
                              clearable
                              placeholder="投资内容"
                          >
                              <el-option
                                  v-for="item in selectionArr"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="投资来源" prop="investSource">
                          <el-select
                              v-model="formInline.investSource"
                              clearable
                              placeholder="投资来源"
                          >
                              <el-option
                                  v-for="item in state.investSourceList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="投资类型" prop="investmentType">
                          <el-select
                              v-model="formInline.investmentType"
                              clearable
                              placeholder="投资类型"
                          >
                              <el-option
                                  v-for="item in state.investmentTypeList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value+''"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="所属业态" prop="typeOfBusiness">
                          <el-select
                              v-model="formInline.typeOfBusiness"
                              clearable
                              placeholder="所属业态"
                          >
                              <el-option
                                  v-for="item in state.typeofBusinessList"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value+''"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="行业类型" prop="industryTypeId">
                          <el-select
                              v-model="formInline.industryTypeId"
                              clearable
                              filterable
                              placeholder="行业类型"
                          >
                              <el-option
                                  v-for="item in state.industryTypeIdList"
                                  :key="item.enumId"
                                  :label="item.enumName"
                                  :value="item.enumId"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="实施主体" prop="companyId">
                          <el-select
                              v-model="formInline.companyId"
                              clearable
                              filterable
                              placeholder="请选择实施主体"
                          >
                              <el-option
                                  v-for="item in state.companyList"
                                  :key="item.companyId"
                                  :label="item.companyName"
                                  :value="item.companyId"
                              />
                          </el-select>
                      </el-form-item>
                  </el-col>

                  <el-col :span="24">
                      <el-form-item
                          label="项目简介"
                          prop="note"
                      >
                          <el-input
                              v-model="formInline.note"
                              show-word-limit
                              type="textarea"
                              placeholder="请输入项目简介"
                          />
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>
      </el-card>
      <div class="button-wrap d-flex a-center j-center m-t20">
          <el-button
              class="button_cancel2"
              @click="goBack"
          >取消</el-button>
          <div>
              <el-button class="button_funtion2" @click="onEdit" v-if="!isEdit">编辑</el-button>
              <el-button class="button_funtion2" @click="onSave" v-else>保存</el-button>
          </div>
      </div>
  </div>
</template>

<script setup>
// 从路由path中获取的
import {useRoute, useRouter} from "vue-router";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElMessage, ElOption, ElRow, ElSelect} from "element-plus";
import {limitInputNum} from "@/common/utils/GlobalUtils";
import {getURLhandler} from "@/views/constructionProjectManage/static/utools";
import { fundManagementApi } from "@/api/businessFinance";
import { investmentProjects, otherApi } from "@/api/investment";
import {
    projectApi,
    projectListApi,
    department,
    publicProject,
    projectConfigApi,
    projectPhase,
} from "@/api/project";
import {assetsApi} from "@/api/assets";

const router = useRouter();
const projectId  = router.currentRoute.value.params.projectId;

const state = reactive({
    baseInfo:{},
    startTime:'',
    endTime:'',
    companyList: [],
    streetList: [],
    projectNatureList: [
        {
            label: "新建项目",
            value: 1,
        },
        {
            label: "续建项目",
            value: 2,
        },
        {
            label: "新设立",
            value: 3,
        },
        {
            label: "续投",
            value: 4,
        },
    ],
    projectNatureList2: [
        {
            label: "新设立",
            value: "3",
        },
        {
            label: "续投",
            value: "4",
        },
    ],
    projectAddTypeList: [
        {
            label: "年初计划",
            value: 1,
        },
        {
            label: "年内新增",
            value: 2,
        },
    ],
    investUseList: [
        {
            label: "经营",
            value: "1",
        },
        {
            label: "管理",
            value: "2",
        },
        {
            label: "其他",
            value: "3",
        },
    ],
    investSourceList: [
        {
            label: "政府投资",
            value: 1,
        },
        {
            label: "公司自投",
            value: 2,
        },
        {
            label: "其他",
            value: 3,
        },
    ],
    planStatusList: [
        {
            label: "计划外",
            value: -1,
        },
        {
            label: "计划内",
            value: 1,
        },
    ],
    projectTypeIdList: [
        {
            label: "股权投资",
            value: "1",
        },
        {
            label: "固定投资",
            value: "2",
        },
    ],
    investmentTypeList: [
        {
            label: "全资",
            value: 1,
        },
        {
            label: "控股",
            value: 2,
        },
        {
            label: "参股",
            value: 3,
        },
    ],
    industryTypeIdList: [],
    //养老、教育、医疗、农贸、综合体、绿道、文体、子公司、其他
    typeofBusinessList: [
        {
            label: "养老",
            value: 1,
        },
        {
            label: "教育",
            value: 2,
        },
        {
            label: "医疗",
            value: 3,
        },
        {
            label: "农贸",
            value: 4,
        },
        {
            label: "综合体",
            value: 5,
        },
        {
            label: "绿道",
            value: 6,
        },
        {
            label: "文体",
            value: 7,
        },
        {
            label: "子公司",
            value: 8,
        },
        {
            label: "其他",
            value: 9,
        },
    ],
    projectId: "",
    projectSetsList: [],
    typeList: [
        {
            label: '股权投资',
            value: 1,
        },
        {
            label: '固定投资',
            value: 2,
        }
    ],
    projectSetIdList: [],
    projectCategoryList: [
        {
            label: "公司自建",
            value: "1",
        },
        {
            label: "政府投资",
            value: "2",
        },
        {
            label: "代建项目",
            value: "3",
        },
    ],
    allDepartmentList: [],
    departmentPersonList: [],
    userByDepartmentList: [],
    projectTypeList: [],
    streerTypeOptionsArr: [],
    dataSource: [], //树行数据
    projectOptionsArr: [], //所有项目
    active: 1,
    success: false, //编辑或添加是否成功
    type: 0, //0新增 1编辑
});

const formInline = reactive({
    time: [],
    streetName: "",
    projectAmount:'',
    yearAmount:'',
});

const route = useRoute();

const projectRules = reactive({
    // companyId: [
    // 	{ required: true, message: "请选择实施主体!", trigger: "change" },
    // ],
    /*note: [
      {
        required: formInline.projectTypeId === '1',
        message: "项目简介不能为空!",
        trigger: "blur",
      },
    ],
    industryTypeId: [
      { required: true, message: "请选择行业类型", trigger: "change" },
    ],
    investmentType: [
      { required: true, message: "请选择投资类型", trigger: "change" },
    ],
    typeId: [{ required: true, message: "请选择项目类型", trigger: "change" }],
    planStatus: [
      { required: true, message: "请选择计划状态", trigger: "change" },
    ],
    investSource: [
      { required: true, message: "请选择投资来源", trigger: "change" },
    ],
    investContent: [
      { required: true, message: "请选择投资内容", trigger: "change" },
    ],*/
    /*  investUse: [
      { required: true, message: '请选择投资用途', trigger: 'change' }
    ],*/
    /*	projectAddType: [
        { required: true, message: "请选择项目新增类型", trigger: "change" },
      ],
      yearAmount: [{ required: true, message: "项目投资金额", trigger: "blur" }],
       projectNature: [
        { required: true, message: '请选择项目性质', trigger: 'change' }
      ],*/
    projectSetId: [
        { required: true, message: "关联项目集不能为空", trigger: "change" },
    ],
    projectName: [
        { required: true, message: "项目名称不能为空", trigger: "blur" },
    ],
    /*	projectCode: [
        { required: true, message: "项目编码不能为空", trigger: "blur" },
      ],*/
    projectTypeId: [
        { required: true, message: "项目分类不能为空", trigger: "change" },
    ],
    /*businessUnit: [
      { required: true, message: "业务单元不能为空", trigger: "change" },
    ],*/
    /*  streetCode: [
      { required: true, message: '项目位置不能为空', trigger: 'blur' }
    ],*/
    /*address: [
      { required: true, message: '项目详细地址不能为空', trigger: 'blur' }
    ],*/
    /*projectAmount: [
      { required: true, message: "拟计划总投额不能为空", trigger: "blur" }
    ],
    typeOfBusiness: [
      { required: true, message: "所属业态不能为空", trigger: "change" },
    ],
    time: [
      { required: true, message: "计划实施时间范围不能为空", trigger: "blur" },
    ],*/
    // responsibleDepartmentId: [
    // 	{ required: true, message: "项目立项部门不能为空", trigger: "change" },
    // ],
    /*responsibleUserId: [
      { required: true, message: "项目负责人不能为空", trigger: "change" },
    ],*/
});

const isEdit = ref(false);
const onEdit = () => {
    isEdit.value = !isEdit.value;
}

const onSave = () => {
    projectConfigApi.addOne(formInline).then(res=>{
        if(res.code==='200'){
            ElMessage.success('编辑成功！');
            isEdit.value = false;
        }
    })
}

/**
 * 查询项目基本信息
 * @param projectId
 * @param callback
 */
const getBaseInfo = (projectId,callback) => {
    reserveInvestmentProjectLibraryApi.getBaseInfo(projectId).then(res=>{
        if(res.code === '200'){
            if(callback)callback(res);
            state.baseInfo = res.data;
        }
    });
}

/**
 * 返回
 */
const goBack = () => {
    // router.push({path:`/investmentProjectManagement/investmentProjects/investmentProjectInformation/investmentProjectsList`});
    router.go(-1);
}

/**
 * 获取数据
 */
const getData = (callback) => {
    getBaseInfo(projectId,(res)=>{
        callback(res);
        for (let key in res.data){
            formInline[key] = res.data[key];
            if(key==='predictStartTime'){
                formInline['time'] = [res.data['predictStartTime'],res.data['predictEndTime']];
            }
        }
    });
}

/**
 * 获取业务单元
 */
const businessUnitList = ref([]);
const getFundBudgetBusinessUnitAll = () => {
    fundManagementApi.getFundBudgetBusinessUnitAll().then((res) => {
        if (res.code === "200") {
            businessUnitList.value = res.data;
        }
    });
};

/**
 * 公司列表
 */
const getCompanyList = () => {
    otherApi.getCompanyList({}).then((res) => {
        if (res.code === "200") {
            state.companyList = res.data;
        }
    });
};

// 获取项目类型
const getProjectTypeVo = () => {
    publicProject.getProjectTypeVo().then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.projectTypeList = data;
        }
    });
};

const getTypeList = (e) => {
    const type = "10" + e;
    projectConfigApi.getTypeList(type).then((res) => {
        if (res.code === '200') {
            state.typeList = res.data.map((item) => {
                return {
                    label: item.typeName,
                    value: item.projectTypeId,
                };
            });
        }
    });
};

// 获取项目集
const getpublicProject = () => {
    projectConfigApi.getProjectSets().then((res) => {
        if (res.code === '200') {
            state.projectSetIdList = res.data.map((item) => {
                return {
                    label: item.projectSetName,
                    value: item.projectSetId,
                };
            });
        }
    });
};

// 获取所有项目集
const getProjectSets = () => {
    fundManagementApi.getProjectSets().then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.projectSetsList = data;
        }
    });
};

// 获取所有部门
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.allDepartmentList = data;
        }
    });
};

//判断是否编辑
let isUpdate = computed(() => {
    if (getURLhandler(route.path).type == 1) {
        return true;
    } else {
        return false;
    }
});

//获取所有项目信息
const projectListApiHandler = () => {
    //新增查询
    //编辑查询
    let obj = {
        projectSetId: "",
    };
    if (isUpdate) {
        obj = {
            projectSetId: getURLhandler(route.path).edit || "",
        };
    }

    projectListApi.getAllList(obj.projectSetId || "").then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.projectOptionsArr = data;
        }
    });
};

const initAreaOptions = (type = "2", cd = "") => {
    // type：1-获取区域 ；2-获取街道
    // cd：获取区域时不传
    assetsApi.getLocations(type, cd).then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            res.data.forEach((item) => {
                item.label = item.name;
                item.value = item.code;
            });
            state.streetList = res.data;
        }
    });
};

/**
 * 行业类型
 */
const getListEnum = () => {
    otherApi.getListEnum({ type: 2 }).then((res) => {
        if (res.code === "200") {
            state.industryTypeIdList = res.data;
        }
    });
};

let allType = [
    {
        label: "建设",
        value: 1,
    },
    {
        label: "装修",
        value: 2,
    },
    {
        label: "设备",
        value: 3,
    },
    {
        label: "新设",
        value: 4,
    },
    {
        label: "收购",
        value: 5,
    },
    {
        label: "增资",
        value: 6,
    },
    {
        label: "其他",
        value: 7,
    },
];
let activeArr1 = allType.filter((item) => {
    let arr = [4, 5, 6, 7];
    return arr.indexOf(item.value) > -1;
});
let activeArr2 = allType.filter((item) => {
    let arr = [1, 2, 3, 7];
    return arr.indexOf(item.value) > -1;
});
let selectionArr = ref([]);
selectionArr.value = allType;
let projectTypeChange = (e) => {
    if (e === "1") {
        selectionArr.value = activeArr1;
    } else if (e === "2") {
        selectionArr.value = activeArr2;
    } else {
        selectionArr.value = allType;
    }
    if (formInline.investContent) {
        let i = selectionArr.value.findIndex((item) => {
            return item.value === formInline.investContent;
        });
        if (i < 0) {
            formInline.investContent = selectionArr.value[0].value;
        }
    }
};

const handelChangeTime = (e) => {
    formInline.predictStartTime = '';
    formInline.predictEndTime = '';
    state.startTime = '';
    state.endTime = '';
    if (e && e.length) {
        formInline.predictStartTime = e[0];
        formInline.predictEndTime = e[1];
        state.startTime = e[0];
        state.endTime = e[1];
    }
};

//位置编号
const streerChange = (e) => {
    state.streetList.forEach((item) => {
        if (item.value == e) {
            formInline.streetName = item.label;
        }
    });
};


const departmentIdChange = (id) => {
    formInline.responsibleUserId = "";
};

// 获取项目 负责人
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
    department.getUserByDepartmentId(responsibleDepartmentId).then((res) => {
        const { code, data, msg } = res;
        if (code === '200') {
            state.departmentPersonList = data;
        }
    });
};


// 监听 项目负责部门 调用 项目负责人
watch(
    () => formInline.departmentId,
    (value) => {
        if (value) {
            getLeaderByDepartmentId(value);
        }
    }
);

onMounted(()=>{
    getListEnum();
    initAreaOptions();
    projectListApiHandler();
    getAllDepartments();
    getProjectSets();
    getpublicProject();
    // getTypeList(getURLhandler(route.path)?.projectType);
    getProjectTypeVo();
    getCompanyList();
    getFundBudgetBusinessUnitAll();
});

defineExpose({
    getData
});
</script>

<style lang="scss" scoped>
.card-box{
  width: 100%;
  .input-width{
    width: 548px;
  }
  .el-form-item-width{
    width: 100%;
  }
}
</style>
